import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { PersonInfoModel } from '../../../../models/person-info-model';
import { InterceptorService } from '../../../../share/interceptor.service';
import { FileUploader } from 'ng2-file-upload'; // 上传文件支持库
@Component({
  selector: 'app-add-basic-info',
  templateUrl: './add-basic-info.component.html',
  styleUrls: ['./add-basic-info.component.css']
})
export class AddBasicInfoComponent implements OnInit {

  constructor(private router: Router,
    private http: InterceptorService) {

  }

  ngOnInit() {
    this.getGrade();
    this.getProvince();
    this.getNativeProvince();
    this.getRelation();
    this.getPerson(); // 页面初始化
    localStorage.removeItem("personPictureURL");
  }



  doNext() {
    this.router.navigateByUrl('/workspace/person-info/add-person-info/add-education'); //education
    this.doAdd(this.modal);
  }

  modal: HTMLElement;
  gradeOptions: string[];//期数集合
  relationOptions: string[]; // 关系集合
  provinceOptions: string[];//省集合
  cityOptions: string[];//市
  countyOrDistrictOptions: String[];//县/区
  provinceNativeOptions: string[];//籍贯省集合
  cityNativeOptions: string[];//籍贯市
  countyOrDistrictNativeOptions: String[];//籍贯县/区
  personInfo: PersonInfoModel = new PersonInfoModel();//个人信息实体
  public defaultPicture: string = 'assets/images/default-avatar.png';//默认图片地址


  editPicture: boolean = true; //修改图片

  // 获得登录学生的个人信息
  getPerson() {
    // let id = 'YtH67q6ykRmfH5F6Re2Fb';//登录人id,假数据
    // let id = '1234567898';
    // let id = 'UpadWgSLPctmPZHdcBUFCV';
    let id = localStorage.getItem('userId');

    // let id=this.personInfo.id; // 管理员查询详情 毕业生id
    let searchUrl = 'graduate-web/personalInfo/selectByPersonId/' + id;


    this.http.get(searchUrl).subscribe(
      res => {
        if (res.json().code == '0000') {
          this.personInfo.id = res.json().data.id;
          this.personInfo.loginId = res.json().data.loginId;
          this.personInfo.name = res.json().data.name;
          this.personInfo.englishName = res.json().data.englishName;
          this.personInfo.grade = res.json().data.grade;
          this.personInfo.gradeName = res.json().data.gradeName;
          this.personInfo.sex = res.json().data.sex;
          this.personInfo.birthday = res.json().data.birthday;
          this.personInfo.email = res.json().data.email;
          this.personInfo.phone = res.json().data.phone;
          this.personInfo.emergPhone = res.json().data.emergPhone;
          this.personInfo.emergName = res.json().data.emergName;
          this.personInfo.emergRelation = res.json().data.emergRelation;
          this.personInfo.wechat = res.json().data.wechat;
          this.personInfo.qq = res.json().data.qq;
          //初始化时间
          if (res.json().data.enterDmtTime == null) {
            this.personInfo.enterDmtTime = this.translateTime(new Date());
          }
          else {
            this.personInfo.enterDmtTime = res.json().data.enterDmtTime;
          }

          this.personInfo.enterCollegeTime = res.json().data.enterCollegeTime;

          if (res.json().data.graduateDmtTime == null) {
            this.personInfo.graduateDmtTime = this.translateTime(new Date());
          }
          else {
            this.personInfo.graduateDmtTime = res.json().data.graduateDmtTime;
          }

          this.personInfo.graduateCollegeTime = res.json().data.graduateCollegeTime;

          this.personInfo.address = res.json().data.address;
          this.personInfo.proviceName = res.json().data.proviceName;
          this.personInfo.provinceId = res.json().data.provinceId;
          this.personInfo.cityName = res.json().data.cityName;
          this.personInfo.cityId = res.json().data.cityId;
          this.personInfo.countyOrDistrictName = res.json().data.countyOrDistrictName;
          this.personInfo.countyOrDistrictId = res.json().data.countyOrDistrictId;
          this.personInfo.timestampTime = res.json().data.timestampTime;
          this.personInfo.professionalField = res.json().data.professionalField;


          //从后台传回实体中，不包括籍贯的字段，后面会增加 TODO
          this.personInfo.nativePlace = res.json().data.nativePlace;
          this.personInfo.provinceNativeId = res.json().data.provinceNativeId
          this.personInfo.provinceNativeName = res.json().data.proviceNativeName;
          this.personInfo.cityNativeName = res.json().data.cityNativeName;
          this.personInfo.cityNativeId = res.json().data.cityNativeId;
          this.personInfo.countyOrDistrictNativeName = res.json().data.countyOrDistrictNativeName;
          this.personInfo.countyOrDistrictNativeId = res.json().data.countyOrDistrictNativeId;

          this.personInfo.remark = res.json().data.remark;

          // this.personInfo.id = this.data[index].relationshipId;
          //将默认图片改为学生图片
          if (res.json().data.pictureUrl == null || res.json().data.pictureUrl == '') {
          } else {
            let el: Element = document.getElementById('wizardPicturePreview');
            let pictureURL = res.json().data.pictureUrl;
            el.setAttribute('src', pictureURL);
            console.log(res.json().data.pictureUrl);
          }
        }
      }
    );
  }

  ch = {
    /** 每周第一天，0代表周日 */
    firstDayOfWeek: 0,
    /** 每周天数正常样式 */
    dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
    /** 每周天数短样式（位置较小时显示） */
    dayNamesShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
    /** 每周天数最小样式 */
    dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
    /** 每月月份正常样式 */
    monthNames: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    /** 每月月份短样式 */
    monthNamesShort: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
  };

  //获得期数
  getGrade() {
    // let dictName: string;
    let gradeUrl = 'graduate-web/dictionary/selectGrade';
    this.http.get(gradeUrl).subscribe(
      res => {
        if (res.json().code == '0000') {
          // 方案1-后端方法
          this.gradeOptions = res.json().data;
          console.log(this.gradeOptions);
        } else {
          // 方案2-假数据
          let data: any[] = [{
            dictName: '5期'
          }, {
            dictName: '6期'
          }, {
            dictName: '7期'
          }, {
            dictName: '8期'
          }, {
            dictName: '9期'
          }, {
            dictName: '10期'
          }, {
            dictName: '11期'
          }];
          this.gradeOptions = data;
        }
      }
    );
  }

  //获得关系
  getRelation() {
    //方案1-后端数据
    let relationUrl = 'graduate-web/dictionary/selectRelation';
    // let relationUrl = 'src/mock-data/seach-dictionary-relation.json';
    this.http.get(relationUrl).subscribe(
      res => {
        if (res.json().code == '0000') {
          // 方案1-后端方法
          this.relationOptions = res.json().data;
          console.log('-============================查询关系+++++++++++++++++++++++++++++++++++++')
          console.log(this.relationOptions);
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: 'JLfyBqa1E7kUpWAiLAAiee',
              dictName: '父子'
            }, {
              id: '57phzcbp5L27k1fhLDWZ1d',
              dictName: '父女'
            }, {
              id: 'Cxmo1fcJsskLWVF1muEJ8o',
              dictName: '母子'
            }, {
              id: 'Y579eZjJ35X8rtM98SSBhP',
              dictName: '母女'
            }, {
              id: 'BYzW9DgWJhhQkAf91DwaKD',
              dictName: '兄弟'
            }, {
              id: '2H3rajKdrLYBEBdARCRNdP',
              dictName: '姐妹'
            }, {
              id: 'SPDhVAraFfHCLrUJwP68Td',
              dictName: '朋友'
            }, {
              id: 'RQepA5sx2uUHLK4192zaFB',
              dictName: '同学'
            }, {
              id: 'VoCATRkLQiYMBzpZi7SypK',
              dictName: '同事'
            }, {
              id: 'N34bUeKGS5JretqhYnewLn',
              dictName: '其他'
            }
          ];
          this.relationOptions = data;
        }
      });
  }
  // -------------------------------------------住址--------------------------------------------
  //获得省
  getProvince() {
    let proviceUrl = 'graduate-web/administrativeRegion/selectProvince';
    this.http.get(proviceUrl).subscribe(
      res => {
        if (res.json().code == '0000') {
          // 方案1-后端方法
          this.provinceOptions = res.json().data;
          // this.getCity(this.provinceOptions[0]);
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: '37',
              name: '河北'
            }
          ];
          this.provinceOptions = data;
        }
        console.log('返回值code' + res.json().code + '省返回值' + this.provinceOptions);
      }
    );
  }

  // 改变住址省，触发查询市
  changeProvince(ProvinceId: string) {
    this.getCity(ProvinceId);
    console.log(ProvinceId);
  }


  // 获得市
  getCity(provinceId) {
    // provinceId = '37';
    // 方案1-后端方法
    let cityUrl = 'graduate-web/administrativeRegion/selectSubRegionById/' + provinceId;
    console.log(provinceId + '省参数');
    this.http.get(cityUrl).subscribe(
      res => {
        if (res.json().code = '0000') {
          this.cityOptions = res.json().data;
          console.log(this.cityOptions);
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: '38',
              pid: '37',
              name: '石家庄'
            }, {
              id: '124',
              pid: '37',
              name: '保定'
            }, {
              id: '197',
              pid: '37',
              name: '廊坊'
            }, {
              id: '150',
              pid: '37',
              name: '张家口'
            }, {
              id: '84',
              pid: '37',
              name: '邯郸'
            }
          ];
          this.cityOptions = data;
        }
      }
    );
  }


  // 改变住址市，触发改变县区
  changeCity(cityId: string) {
    this.getCountyOrDistrict(cityId);
  }
  // 获得县/区
  getCountyOrDistrict(cityId) {
    // cityId = '38';
    // 方案1-后端方法
    let countyOrDistrictUrl = 'graduate-web/administrativeRegion/selectSubRegionById/' + cityId;
    this.http.get(countyOrDistrictUrl).subscribe(
      res => {
        if (res.json().code == '0000') {
          this.countyOrDistrictOptions = res.json().data;
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: '48',
              pid: '38',
              name: '正定县'
            }, {
              id: '203',
              pid: '197',
              name: '大城县'
            }, {
              id: '55',
              pid: '38',
              name: '平山县'
            }, {
              id: '199',
              pid: '197',
              name: '广阳区'
            }, {
              id: '198',
              pid: '197',
              name: '安次区'
            }, {
              id: '43',
              pid: '38',
              name: '裕华区'
            }, {
              id: '39',
              pid: '38',
              name: '长安区'
            }
          ];
          this.countyOrDistrictOptions = data;
        }
      }
    );
  }
  // ----------------------------------------------籍贯--------------------------------------------------
  //籍贯获得省
  getNativeProvince() {
    let proviceUrl = 'graduate-web/administrativeRegion/selectProvince';
    this.http.get(proviceUrl).subscribe(
      res => {
        if (res.json().code == '0000') {
          // 方案1-后端方法
          this.provinceNativeOptions = res.json().data;

        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: '37',
              name: '河北'
            }
          ];
          this.provinceNativeOptions = data;
        }
        console.log('返回值code' + res.json().code + '籍贯省返回值' + this.provinceNativeOptions);
      }
    );
  }

  // 籍贯改变住址省，触发查询市
  changeNativeProvince(provinceNativeId: string) {
    this.getNativeCity(provinceNativeId);
    console.log(provinceNativeId);
  }
  // 籍贯获得市
  getNativeCity(provinceNativeId) {
    // provinceId = '37';
    // 方案1-后端方法
    let cityUrl = 'graduate-web/administrativeRegion/selectSubRegionById/' + provinceNativeId;
    console.log(provinceNativeId + '省参数');
    this.http.get(cityUrl).subscribe(
      res => {
        if (res.json().code = '0000') {
          this.cityNativeOptions = res.json().data;
          console.log(this.cityNativeOptions);
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: '38',
              pid: '37',
              name: '石家庄'
            }, {
              id: '124',
              pid: '37',
              name: '保定'
            }, {
              id: '197',
              pid: '37',
              name: '廊坊'
            }, {
              id: '150',
              pid: '37',
              name: '张家口'
            }, {
              id: '84',
              pid: '37',
              name: '邯郸'
            }
          ];
          this.cityNativeOptions = data;
        }
      }
    );
  }

  // 籍贯改变住址市，触发改变县区
  changeNativeCity(cityNativeId: string) {
    this.getNativeCountyOrDistrict(cityNativeId);
  }

  // 籍贯获得县/区
  getNativeCountyOrDistrict(cityNativeId) {
    // cityId = '38';
    // 方案1-后端方法
    let countyOrDistrictUrl = 'graduate-web/administrativeRegion/selectSubRegionById/' + cityNativeId;
    this.http.get(countyOrDistrictUrl).subscribe(
      res => {
        if (res.json().code == '0000') {
          this.countyOrDistrictNativeOptions = res.json().data;
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: '48',
              pid: '38',
              name: '正定县'
            }, {
              id: '203',
              pid: '197',
              name: '大城县'
            }, {
              id: '55',
              pid: '38',
              name: '平山县'
            }, {
              id: '199',
              pid: '197',
              name: '广阳区'
            }, {
              id: '198',
              pid: '197',
              name: '安次区'
            }, {
              id: '43',
              pid: '38',
              name: '裕华区'
            }, {
              id: '39',
              pid: '38',
              name: '长安区'
            }
          ];
          this.countyOrDistrictNativeOptions = data;
        }
      }
    );
  }


  /**
    * 判断字符串是否为 null或为 '' 值，是则返回true，否返回false 郑晓东 2017年11月20日17点43分
    * @param obj 字符串
    */
  isStrEmpty(obj: string) {
    if (obj == undefined || obj == null || obj.trim() == '') {
      return true;
    }
    return false;
  }

  display: boolean = false;
  messages: '';
  /**
   * 提示框
   */
  showDialog(string) {
    this.messages = string;
    this.display = true;
    let com = this;
    var t = setTimeout(function () { com.display = false }, 1500);
  }

  /**
   * 保存头像前，删除之前的所有头像
   * @param id  用户id
   */
  deletePicture(id) {
    // let operator = '徐玲博';
    let operator = localStorage.getItem('userName');
    let url = 'graduate-web/picture/deletePictureById' + '/' + id + '/' + operator;
    let body = JSON.stringify(null);
    this.http.post(url, body).subscribe(
      res => {
        if (res.json().code == '0000') {
          console.log('-------------------------图片删除返回值-----------------------------');
          console.log(res.json().data);

        }
      }
    );
  }

  /**
   * 添加个人信息
   * @param addModal  个人信息
   */
  doAdd(addModal: HTMLElement) {
    // let pictureIP = 'http://192.168.22.64/';
    // 保存头像前，删除之前的所有头像
    if (localStorage.getItem('personPictureURL') != undefined) {
      this.deletePicture(this.personInfo.id);
      // 图片路径
      this.personInfo.pictureUrl = localStorage.getItem('personPictureURL');
    }

    if (this.personInfo == null) {
      this.showDialog('内容为空，请填写数据！');
      return;
    }
    let addUrl = 'graduate-web/personalInfo/updatePersonInfo/';
    // 获得详细的住址地址
    let address = this.personInfo.proviceName
      + this.personInfo.cityName
      + this.personInfo.countyOrDistrictName

    // 获得详细的籍贯地址
    let nativePlace = this.personInfo.provinceNativeName
      + this.personInfo.cityNativeName
      + this.personInfo.countyOrDistrictNativeName


    if (!this.checkOutDate(this.translateTime(new Date(this.personInfo.enterDmtTime)), this.translateTime(new Date(this.personInfo.graduateDmtTime)))) {
      this.showDialog('进入大米时代的时间不得晚于从大米时代毕业时间！');
      return;
    };
    this.personInfo.enterDmtTime = this.translateTime(new Date(this.personInfo.enterDmtTime));
    this.personInfo.graduateDmtTime = this.translateTime(new Date(this.personInfo.graduateDmtTime));
    let body = JSON.stringify(this.personInfo);
    console.log(body);
    this.http.post(addUrl, body).toPromise().then(
      res => {
        if (res.json().code = '0000') {
          if (res.json().data > 0) {
            this.showDialog('您的信息保存成功！');
            localStorage.removeItem("personPictureURL");
          }
        }
      }
    );
  }

  /**
   * 检查两日期的有效性（后日期不得早于前日期） 郑晓东 2018年2月21日
   */
  checkOutDate(inDate: string, outDate: string) {
    if (outDate >= inDate) {
      return true;
    }
    return false;
  }

  /**
   * 时间转化
   * @param date 日期
   */
  translateTime(date) {
    var seperator1 = '-';
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate;
    }
    return year + seperator1 + month + seperator1 + strDate + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
    // return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(); 
  }

  /*****************************上传图片*******************************************/
  //上传配置
  public uploader: FileUploader = new FileUploader({
    url: this.http.getServerUrl("graduate-web/picture/FileUpload"),
    method: 'POST',
    removeAfterUpload: true
    // itemAlias: 'file',
    // allowedFileType:['.jpeg','.jpg','.png','.bmp','.gif']
  });

  public selectedFileOnChanged() {
    this.editPicture = !this.editPicture; //
    //上传文件
    this.uploader.queue[0].onSuccess = function (response, status, headers) {
      //上传文件成功
      if (status == 200) {
        let picServerUrl:string='http://tfjybj.com/';//正式
        // let picServerUrl: string = 'http://192.168.22.64/';//开发联调
        //let picServerUrl:string='http://192.168.22.65/';//测试
        //上传文件后获取服务器返回的数据
        let tempRes = JSON.parse(response);
        //修改页面图片
        let pictureURL: string = tempRes.data;
        let el: Element = document.getElementById('wizardPicturePreview');
        el.setAttribute('src', picServerUrl + pictureURL);//拼接url
        console.log(el.setAttribute);
        let el2: Element = document.getElementById('wizard-picture');
        el2.setAttribute('class', 'hidePicture');
        //存储图片路径
        localStorage.setItem('personPictureURL', pictureURL);

      } else {
        // 上传文件后获取服务器返回的数据错误
        this.msgs = [{
          severity: 'error',
          summary: '提示',
          detail: '上传图片失败！'
        }]
      }

    };
    // 开始上传
    this.uploader.queue[0].upload()
  };


}
